#!/usr/bin/env python
# -*- coding: utf8 -*-

'''
# =======
# User: luwei
# Date: 11-4-21
# Time: 上午8:57
# email = luw2007@gmail.com
# =======
'''

# Imports
# =======
import adns
import sys

def get_address_by_server(domain, name_server):
    serverinfo = "nameserver " + name_server
    s = adns.init(adns.iflags.noautosys,sys.stderr,serverinfo)
    # returns a tuple
    resolve = s.synchronous(domain,adns.rr.A)
    return resolve[3]

def check_domain_resolve(domain,all_servers):

    if all_servers:
        servers = [['内网','172.20.23.2'],
                   ['北京联通','202.106.46.151'],
                   ['中企智能','123.100.6.157','123.100.6.156'],
                   ['中企动力','210.51.171.200','210.51.171.201'],
                   ['台湾中华电信','168.95.1.1'],
                   ['谷歌dns','8.8.8.8']]
    else:
        servers = [ ['北京联通','202.106.46.151'],['谷歌dns','8.8.8.8']]
    address = []
    for i in xrange(len(servers)):
        for j in xrange(len(servers[i])-1):
            domain_list = get_address_by_server(domain,servers[i][j+1])
            address.append([servers[i][0]+ "@" + servers[i][j + 1], list(domain_list)])
    return address

def check_domain_resolve_input():
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option( '-d', "--domain", dest="domain", default="www.bathroom-line.com", help="domain name", metavar="DOMAIN")
    parser.add_option( '-a', "--all", dest="all_servers", action="store_true", default=False, help="check for all servers", metavar="all_server")

    (options, args) = parser.parse_args()
    #print "options: " , options , "args: " , args
    if args:
        domain = args[0]
    else:
        domain = options.domain
    check = check_domain_resolve(domain,options.all_servers)
    print "#", domain, "的解析"
    for i in xrange(len(check)):
        for j in xrange(len(check[i])-1):
            print check[i][j],"|",
        for k in xrange(len(check[i][1])):
            print check[i][1][k],
        print
    sys.exit(not check)

def get_address_by_server_type(domain,type, name_server):
    '''type
A	1
HINFO	13
none	0
RP	131089
SRVraw	33
ADDR	65537
mail822
131072
NS	65538
RPraw	17
TXT	16
CNAME	5
NSraw	2
SOA	131078
typemask	65535
deref	65536
MX	65551
PTR	65548
SOAraw	6
unknown	262144
MXraw	15
PTRraw	12
SRV	65569
'''
    dict_type = {"A":1,"HINFO":13,"none":0,"RP":131089,"SRVraw":33,"ADDR":65537,"mail822":131072,"NS":65538,"RPraw":17,"TXT":16,"CNAME":5,"NSraw":2,"SOA":131078,"typemask":65535,"deref":65536,"MX":65551,"PTR":65548,"SOAraw":6,"unknown":262144,"MXraw":15,"PTRraw":12,"SRV":65569}
    try:
        type = dict_type[type]
    except :
        print "type error"
        sys.exit(1)
    
    serverinfo = "nameserver " + name_server
    s = adns.init(adns.iflags.noautosys,sys.stderr,serverinfo)
    # returns a tuple
    resolve = s.synchronous(domain,type)
    #print resolve
    return (resolve[1],resolve[3])

def check_domain_type_resolve(domain,type,all_servers):
    if all_servers == 3:
        servers = [['内网','172.20.23.2'],
                   ['北京联通','202.106.46.151'],
                   ['谷歌dns','8.8.8.8'],
                   ['台湾中华电信','168.95.1.1'],
                   ['中企智能','123.100.6.157','123.100.6.156'],
                   ['中企动力','210.51.171.200','210.51.171.201']]
    elif all_servers == 2:
        servers = [['内网','172.20.23.2'],['北京联通','202.106.46.151'],['谷歌dns','8.8.8.8'],['中企智能1','123.100.6.156']]
    elif all_servers == 1:
         servers = [['内网','172.20.23.2'],['北京联通','202.106.46.151']]
    else:
        servers = [['内网','172.20.23.2']]
    address = []
    #特殊处理ns情况
    if type == "NS":
        servers = [['内网','172.20.23.2']]
    
    for i in xrange(len(servers)):
        for j in xrange(len(servers[i])-1):
            domain_list = get_address_by_server_type(domain,type,servers[i][j+1])
            #print domain_list[0], "-|-", domain_list[1]
            address.append([servers[i][0]+"@" + servers[i][j + 1], domain_list[0], domain_list[1]])
            #address.append([servers[i][0]+ "-" + str(j+1) + "@" + servers[i][j + 1], domain_list[0], domain_list[1]])
    return address

def check_domain_type_resolve_input():
    from optparse import OptionParser
    
    parser = OptionParser()
    parser.add_option( '-d', "--domain", dest="domain", default="google.com.hk", help="domain name", metavar="DOMAIN")
    parser.add_option( '-a', "--all", dest="all_servers", default=0, help="int for all servers [1/2]", metavar="all_server")
    parser.add_option( '-A', "--ALL", dest="ALL_servers", default=False,action="store_true", help="set all_servers = 1 for all servers ", metavar="ALL_serverS")
    parser.add_option( '-t', "--type", dest="type", default="A", help="type for all servers", metavar="TYPE")

    (options, args) = parser.parse_args()
    #print "options: " , options , "args: " , args
    if args:
        domain = args[0]
    else:
        domain = options.domain
    if options.ALL_servers:
        options.all_servers = 2
    check = check_domain_type_resolve(domain,options.type.upper(),int(options.all_servers))
    print "#", domain, "关于" ,options.type.upper(),"的解析:"

    for i in xrange(len(check)):
        print str(str(i+1)+'.'),
        if check[i][2]:
            for j in xrange(len(check[i])-1):
                if check[i][j]:
                    print check[i][j],'\r\n\t',
            if options.type.upper() == "NS":
                print '\r\n\t'.join([k[0]+": "+k[2][0][1] for k in  check[i][2]]),
            elif options.type.upper() == "MX":
                print '\r\n\t'.join([str(k[0]) +"=> "+k[1][0]+": "+k[1][2][0][1] for k in  check[i][2]]),
            else:
                print ' | '.join([k for k in  check[i][2]])
            print
        else:
            print check[i][0],'\r\n\tNone'
    sys.exit(not check)

def main():
    '''test main'''
    print "done"


if __name__ == '__main__':
    check_domain_type_resolve_input()
    main()



